<template>
  <div id="note" class="detail">
    <NoteSlidebar @update:notes="(val) => (notes = val)"></NoteSlidebar>

    <div class="note-detail">
      <div class="note-empty" v-show="!curNote.id">请选择笔记</div>
      <div class="note-detail-ct" v-show="curNote.id">
        <div class="note-bar">
          <span> 创建日期: {{ curNote.friendlyUpdatedAt }}</span>
          <span> 更新日期: {{ curNote.friendlyCreatedAt }}</span>
          <span> {{ statusText }}</span>
          <span class="iconfont icon-delete" @click="onDeleteNote"></span>
          <span
            class="iconfont icon-fullscreen"
            @click="isShowPreview = !isShowPreview"
          ></span>
        </div>
        <div class="note-title">
          <input
            type="text"
            placeholder="输入标题"
            v-model="curNote.title"
            @input="onUpdateNote"
            @keydown="statusText = '正在输入...'"
          />
        </div>
        <div class="editor">
          <textarea
            placeholder="输入内容, 支持 markdown 语法"
            v-model="curNote.content"
            @input="onUpdateNote"
            @keydown="statusText = '正在输入...'"
            v-show="!isShowPreview"
          ></textarea>
          <div
            class="preview markdown-body"
            v-html="previewContent"
            v-show="isShowPreview"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import NoteSlidebar from "@/components/NoteSlidebar";
import _ from "lodash";

import MarkdownIt from "markdown-it";
import { mapActions, mapGetters, mapMutations } from "vuex";
const md = new MarkdownIt();
export default {
  beforeRouteUpdate(to, from, next) {
    this.setCurNote({ curNoteId: to.query.noteId });
    next();
  },
  data() {
    return {
      statusText: "笔记未改动",
      isShowPreview: false,
    };
  },
  computed: {
    ...mapGetters(["curNote", "notes"]),

    previewContent() {
      return md.render(this.curNote.content || "");
    },
  },
  methods: {
    ...mapMutations(["setCurNote"]),
    ...mapActions(["updateNote", "deleteNote", "checkLogin"]),
    //节流函数
    onUpdateNote: _.debounce(function () {
      this.updateNote({
        noteId: this.curNote.id,
        title: this.curNote.title,
        content: this.curNote.content,
      })
        .then((res) => {
          this.statusText = "保存成功";
        })
        .catch((data) => {
          this.statusText = "保存失败";
        });
    }, 1000),
    onDeleteNote() {
      this.deleteNote({ noteId: this.curNote.id }).then(() => {
        this.$router.replace({ path: "/note" });
      });
    },
  },
  components: {
    NoteSlidebar,
  },
  created() {
    this.checkLogin({ path: "/login" });
    // if (this.notes.length > 0) {
    //   this.setCurNote({ curNoteId: this.notes[0].id });
    // }
  },
};
</script>
<style lang="less"  >
#note {
  display: flex;
  align-items: stretch;
  background-color: #fff;
  flex: 1;
}
@import url("../assets/note-detail.less");
</style>
